package com.ifp.opengate.boot.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import com.ifp.core.log.Trace;
import com.ifp.core.util.StringUtil;

public class HttpUtils {

    public static String postWithParams(String url, Map<String, String> paramMap) {

        // 参数
        StringBuilder params = new StringBuilder();
        if (paramMap != null) {
            paramMap.forEach((key, value) -> {
                try {
                    value = StringUtil.hasText(value) ? URLEncoder.encode(value, "utf-8") : "";
                } catch (UnsupportedEncodingException e) {
                    Trace.logError(Trace.MODULE_COMMON, e.toString());
                }
                params.append(key).append("=").append(value).append("&");
            });
            params.setLength(params.length() - 1);
        }

        // 创建Post请求
        HttpPost httpPost = new HttpPost(url + "?" + params);
        httpPost.setHeader("Content-Type", "application/json;charset=utf8");

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build();
            CloseableHttpResponse response = httpClient.execute(httpPost);) {

            HttpEntity responseEntity = response.getEntity();

            if (responseEntity != null) {
                return EntityUtils.toString(responseEntity);
            }

        } catch (Exception e) {
            Trace.logError(Trace.MODULE_CONNECT, "通讯异常: {}", e);
        }

        return "";

    }

}
